#import <QuartzCore/QuartzCore.h>
#import "RootViewController.h"
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#import "HJObjManager.h"
#import "HJManagedImageV.h"
#import "firstviewcontroller.h"
#import "Detailsprogview.h"

@implementation RootViewController

@synthesize itemsToDisplay;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
		
	// Super
	[super viewDidLoad];
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
	
	// Setup
	self.title = @"Loading...";
	formatter = [[NSDateFormatter alloc] init];
	[formatter setDateStyle:NSDateFormatterShortStyle];
	[formatter setTimeStyle:NSDateFormatterShortStyle];
	parsedItems = [[NSMutableArray alloc] init];
	self.itemsToDisplay = [NSArray array];
	
    self.tableView.rowHeight = 75;
    
    objMan = [[HJObjManager alloc] initWithLoadingBufferSize:10 memCacheSize:25];
    
	// Refresh button
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply 
																							target:self 
																							action:@selector(back)] autorelease];
    
    
    self.title = @"Barcelona";
	NSURL *feedURL = [NSURL URLWithString:@"http://www.ingravitymedia.com/actualite.rss"];
    
	feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
	feedParser.delegate = self;
	feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
	feedParser.connectionType = ConnectionTypeAsynchronously;
	[feedParser parse];

    // this is a custom label for this view's title
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
	[titleLabel setBackgroundColor:[UIColor clearColor]];
	[titleLabel setFont:[UIFont boldSystemFontOfSize:17.0]];
	[titleLabel setTextColor:[UIColor whiteColor]];
	[titleLabel setText:self.title];
	[titleLabel sizeToFit];
	[titleLabel setCenter:[self.navigationItem.titleView center]];
	[self.navigationItem setTitleView:titleLabel];
	[titleLabel release];
    
    firstviewcontroller *sampleView = [[[firstviewcontroller alloc] init] autorelease];
    [sampleView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self presentModalViewController:sampleView animated:YES];
    
}

#pragma mark -
#pragma mark Parsing


//back
- (void)back {
    firstviewcontroller *sampleView = [[[firstviewcontroller alloc] init] autorelease];
    [sampleView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self presentModalViewController:sampleView animated:YES];
    
}


// Reset and reparse
- (void)refresh {
	self.title = @"Refreshing...";
	[parsedItems removeAllObjects];
	[feedParser stopParsing];
	[feedParser parse];
	self.tableView.userInteractionEnabled = NO;
	self.tableView.alpha = 0.2;
}

#pragma mark -
#pragma mark MWFeedParserDelegate

- (void)feedParserDidStart:(MWFeedParser *)parser {
	//NSLog(@"Started Parsing: %@", parser.url);
}

- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
	//NSLog(@"Parsed Feed Info: “%@”", info.title);
	//self.title = info.title;
}

- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
	if (item) [parsedItems addObject:item];	
}

- (void)feedParserDidFinish:(MWFeedParser *)parser {
	//NSLog(@"Finished Parsing%@", (parser.stopped ? @" (Stopped)" : @""));
	self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
						   [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO] autorelease]]];
	self.tableView.userInteractionEnabled = YES;
	self.tableView.alpha = 1;
	[self.tableView reloadData];
}

- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
	//NSLog(@"Finished Parsing With Error: %@", error);
	self.title = @"Failed";
	self.itemsToDisplay = [NSArray array];
	[parsedItems removeAllObjects];
	self.tableView.userInteractionEnabled = YES;
	self.tableView.alpha = 1;
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return itemsToDisplay.count;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    HJManagedImageV* myimage;
    UILabel *textLabel;
    UILabel *subLabel;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        myimage = [[[HJManagedImageV alloc] initWithFrame:CGRectMake(5,5,60,60)] autorelease];
		myimage.tag = 999;
		[cell addSubview:myimage];
        
        textLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 0.0, 215, 50)];
        textLabel.tag = 998;
        textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:13.0];
        textLabel.contentMode = UIViewContentModeScaleAspectFill;
        textLabel.lineBreakMode = UILineBreakModeWordWrap;
        textLabel.numberOfLines = 2;
        
        subLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 50, 215, 30)];
        subLabel.tag = 997;
        subLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:11.0];
        subLabel.contentMode = UIViewContentModeScaleAspectFill;
        subLabel.lineBreakMode = UILineBreakModeWordWrap;
        subLabel.numberOfLines = 2;
        
        [cell addSubview:textLabel];
        [textLabel release];
        
        [cell addSubview:subLabel];
        [subLabel release];

    } else {
        subLabel  = (UILabel *) [cell viewWithTag:997];
        textLabel = (UILabel *) [cell viewWithTag:998];
        
        // async manage all images for the items of the tableview
        myimage = (HJManagedImageV*)[cell viewWithTag:999];
		[myimage clear];        
        
    }
    
    MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
    
	if (item) {

        myimage.url = [NSURL URLWithString:[[item.enclosures objectAtIndex:0] objectForKey:@"url"]];
        [objMan manage:myimage];
        
        textLabel.text = [item.title stringByDecodingHTMLEntities];
        NSMutableString *subtitle = [NSMutableString string];
        if (item.date) [subtitle appendFormat:@"%@: ", [formatter stringFromDate:item.date]];
        subLabel.text = subtitle;    

	}

    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

/*	// Show detail
	DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
	detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:detail animated:YES];
	[detail release];
	*/
    
    // Show detail
	Detailsprogview *detail = [[Detailsprogview alloc] initWithNibName:@"Detailsprogview" bundle:[NSBundle mainBundle]];
	//detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
	[self.navigationController pushViewController:detail animated:YES];
	[detail release];

                      
    
	// Deselect
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    switch (toInterfaceOrientation){
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            return YES;
        default:
            return NO;
    }
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[formatter release];
	[parsedItems release];
	[itemsToDisplay release];
	[feedParser release];
    [super dealloc];
}

@end
